import os
from datetime import datetime,timedelta
from flask import render_template, request, flash, redirect, url_for,jsonify, g, send_from_directory,Blueprint
from models import app, User, Jobnumber, Category, Subcategory,Task,Holiday, db
from sqlalchemy.sql import func, extract
from flask_login import LoginManager,login_required, login_user, logout_user, current_user
from flask_wtf import FlaskForm
from functools import wraps


bp_admin = Blueprint('bp_admin', __name__)

# 神奇的装饰器
def admin_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        if not current_user.admin:
            flash("权限不足!", category="danger")
            return redirect(url_for('login'), code=302)
        return f(*args, **kwargs)
    return decorated


@bp_admin.route("/admin/holidays", methods=['GET'])
@login_required
@admin_required
def holidays():
    holidays = db.session.query(Holiday.id, Holiday.date, Holiday.desc,
        Holiday.createtime, Holiday.edittime, Holiday.delete, Holiday.isworkday).all()
    return render_template('admin/holidays.html',holidays=holidays)

@bp_admin.route("/admin/holiday", methods=['GET','POST'])
@login_required
@admin_required
def holiday_create():
    if request.method == 'GET':
        return render_template('admin/holiday_create.html')
    if request.method == 'POST':
        date = request.form.get('date')
        desc = request.form.get('desc')
        isworkday = request.form.get('isworkday')

        if not date:
            flash("日期不能为空", category="danger")
            return redirect(url_for('bp_admin.holiday_create'), code=302)
        if not desc:
            flash("描述不能为空", category="danger")
            return redirect(url_for('bp_admin.holiday_create'), code=302)

        date = datetime.strptime(date, '%Y-%m-%d')
        holidays = db.session.query(Holiday.delete).filter(Holiday.date == date).all()
        if holidays:
            if holidays[0][0]:
                flash("日期已存在，且已删除，请自行恢复", category="danger")
                return redirect(url_for('bp_admin.holiday_create'), code=302)
            else:
                flash("日期已存在", category="danger")
                return redirect(url_for('bp_admin.holiday_create'), code=302)

        isworkday = True if isworkday else False

        try:
            holiday = Holiday(date=date, desc=desc, isworkday=isworkday)
            db.session.add(holiday)
            db.session.commit()
            flash("假日创建成功。", category="success")
            return redirect(url_for('bp_admin.holidays'), code=302)
        except Exception as e:
            flash(e, category="danger")
            return redirect(url_for('bp_admin.holiday_create'), code=302)

@bp_admin.route("/admin/holiday/<holidayid>", methods=['GET','POST'])
@login_required
@admin_required
def holiday_edit(holidayid):
    if request.method == 'GET':
        holiday = db.session.query(Holiday.id, Holiday.date, Holiday.desc, Holiday.isworkday).filter_by(id=holidayid).first()
        if holiday:
            return render_template('admin/holiday_edit.html',holiday=holiday)
        else:
            flash("假日不存在!", category="danger")
            return redirect(url_for('bp_admin.holidays'), code=302)
    if request.method == 'POST':
        desc = request.form.get('desc')
        isworkday = request.form.get('isworkday')
        if not desc:
            flash("描述不能为空", category="danger")
            return redirect(url_for('bp_admin.holiday_create'), code=302)
        isworkday = True if isworkday else False
        try:
            holiday = Holiday.query.filter_by(id=holidayid).first()
            holiday.desc = desc
            holiday.isworkday = isworkday
            holiday.edittime = datetime.now()
            db.session.commit()
            flash("假日修改成功。", category="success")
            return redirect(url_for('bp_admin.holidays'), code=302)
        except Exception as e:
            flash(e, category="danger")
            return redirect(url_for('bp_admin.holiday_edit',holidayid=holidayid), code=302)


@bp_admin.route("/admin/holiday/<holidayid>/delete")
@login_required
@admin_required
def holiday_delete(holidayid):
    holiday = Holiday.query.filter_by(id=holidayid).first()
    if not holiday:
        flash("假日不存在", category="danger")
        return redirect(url_for('bp_admin.holidays'), code=302)
    try:
        holiday.delete = not holiday.delete
        db.session.commit()
        flash("修改成功。" , category="success")
        return redirect(url_for('bp_admin.holidays'), code=302)
    except Exception as e:
        flash(e, category="danger")
        return redirect(url_for('bp_admin.holidays'), code=302)


@bp_admin.route("/admin/users", methods=['GET'])
@login_required
@admin_required
def admin_users():
    users = db.session.query(User.id,User.no,User.name, User.position, User.delete, User.admin).all()
    return render_template('admin/users.html',users=users)

@bp_admin.route("/admin/user", methods=['GET','POST'])
@login_required
@admin_required
def admin_user_create():
    if request.method == 'GET':
        return render_template('admin/user_create.html')
    if request.method == 'POST':
        no = request.form.get('no').strip()
        name = request.form.get('name').strip()
        position = request.form.get('position').strip()
        position = position if position else ''
        if not no:
            flash("工号不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_user_create'), code=302)
        if User.query.filter_by(no=no).first():
            flash("工号已存在。", category="danger")
            return redirect(url_for('bp_admin.admin_user_create'), code=302)
        if not name:
            flash("姓名不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_user_create'), code=302)
        try:
            user = User(no=no , name=name , password='123456', position=position)
            db.session.add(user)
            db.session.commit()
            flash("用户创建成功。", category="success")
            return redirect(url_for('bp_admin.admin_users'), code=302)
        except Exception as e:
            flash(e, category="danger")
            return redirect(url_for('bp_admin.admin_user_create'), code=302)

@bp_admin.route("/admin/user/<userid>", methods=['GET','POST'])
@login_required
@admin_required
def admin_user_edit(userid):
    if request.method == 'GET':
        if userid == '1':
            flash("不能修改管理员。", category="danger")
            return redirect(url_for('bp_admin.admin_users'), code=302)
        user = db.session.query(User.id, User.no, User.name, User.position).filter_by(id=userid).first()
        if user:
            return render_template('admin/user_edit.html',user=user)
        else:
            flash("用户不存在!", category="danger")
            return redirect(url_for('bp_admin.admin_users'), code=302)
    if request.method == 'POST':
        no = request.form.get('no').strip()
        name = request.form.get('name').strip()
        position = request.form.get('position').strip()
        position = position if position else ''
        if not name:
            flash("姓名不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_user_edit',userid=userid), code=302)
        try:
            # user = User.query.filter_by(no=no).first()
            user = User.query.filter_by(id=userid).first()
            user.name = name
            user.position = position
            db.session.commit()
            flash("修改成功。", category="success")
            return redirect(url_for('bp_admin.admin_users',userid=userid), code=302)
        except Exception as e:
            flash(e, category="danger")
            return redirect(url_for('bp_admin.admin_user_edit',userid=userid), code=302)


@bp_admin.route("/admin/user/<userid>/resetpw")
@login_required
@admin_required
def admin_user_resetpw(userid):
    if userid == '1':
        flash("不能修改管理员。", category="danger")
        return redirect(url_for('bp_admin.admin_users'), code=302)
    user = User.query.filter_by(id=userid).first()
    if not user:
        flash("用户不存在", category="danger")
        return redirect(url_for('bp_admin.admin_users'), code=302)
    try:
        user.password = '123456'
        db.session.commit()
        flash("修改成功。" , category="success")
        return redirect(url_for('bp_admin.admin_users'), code=302)
    except Exception as e:
        flash(e, category="danger")
        return redirect(url_for('bp_admin.admin_users'), code=302)


@bp_admin.route("/admin/user/<userid>/delete")
@login_required
@admin_required
def admin_user_delete(userid):
    if userid == '1':
        flash("不能修改管理员。", category="danger")
        return redirect(url_for('bp_admin.admin_users'), code=302)
    user = User.query.filter_by(id=userid).first()
    if not user:
        flash("用户不存在", category="danger")
        return redirect(url_for('bp_admin.admin_users'), code=302)
    try:
        user.delete = not user.delete
        db.session.commit()
        flash("修改成功。" , category="success")
        return redirect(url_for('bp_admin.admin_users'), code=302)
    except Exception as e:
        flash(e, category="danger")
        return redirect(url_for('bp_admin.admin_users'), code=302)

@bp_admin.route("/admin/user/<userid>/view")
@login_required
@admin_required
def admin_user_view(userid):
    user = User.query.filter_by(id=userid).first()
    if not user:
        flash("用户不存在", category="danger")
        return redirect(url_for('bp_admin.admin_users'), code=302)
    return render_template('admin/user_view.html',user=user)

@bp_admin.route("/admin/user/<userid>/ajaxs/events")
@login_required
@admin_required
def get_user_events2(userid):
    start = request.args.get('start')
    end = request.args.get('end')
    tasks = db.session.query(Task.id, Task.title, Task.remark, Task.userid, Task.categoryid, Task.subcategoryid, Task.jobnumberid, Task.manhour, Task.tasktime, Task.createtime, Task.edittime, Task.delete, User.name, Category.name,Category.color, Subcategory.name, Subcategory.color, Jobnumber.name).filter_by(userid=userid).filter_by(delete=False).filter(Task.tasktime <= end).filter(Task.tasktime >= start).join(Jobnumber, Jobnumber.id==Task.jobnumberid).join(User, User.id==Task.userid).join(Category, Category.id==Task.categoryid).join(Subcategory, Subcategory.id==Task.subcategoryid).all()
    data = []
    for task in tasks:
        data.append({
            'id':task.id,
            'title':task.title,
            'jobnumberid':task.jobnumberid,
            'remark':task.remark,
            'manhour':task.manhour,
            'categoryid':task.categoryid,
            'subcategoryid':task.subcategoryid,
            'start':task.tasktime.strftime('%Y-%m-%d'),
            'color': '#{}'.format(task[14])
            })
        # print(task)
    return jsonify(data)

@bp_admin.route("/admin/user/<userid>/ajaxs/count")
@login_required
@admin_required
def get_user_day_count2(userid):
    start = request.args.get('start')
    end = request.args.get('end')
    tasks = db.session.query(Task.tasktime, func.sum(Task.manhour).label('total')).filter_by(userid=userid).filter_by(delete=False).filter(Task.tasktime <= end).filter(Task.tasktime >= start).group_by(Task.tasktime).all()
    data = {}
    for task in tasks:
        d = task.tasktime.strftime('%Y-%m-%d')
        h = float(task.total)
        data[d] = h

    return jsonify(data)





# jobnumber routers....
@bp_admin.route("/admin/jobnumbers", methods=['GET'])
@login_required
@admin_required
def admin_jobnumbers():
    jobnumbers = db.session.query(Jobnumber.id,Jobnumber.name,Jobnumber.desc,Jobnumber.delete).all()
    return render_template('admin/jobnumbers.html',jobnumbers=jobnumbers)

@bp_admin.route("/admin/jobnumber", methods=['GET','POST'])
@login_required
@admin_required
def admin_jobnumber_create():
    if request.method == 'GET':
        return render_template('admin/jobnumber_create.html')
    if request.method == 'POST':
        name = request.form.get('name').strip()
        name = name.upper()
        desc = request.form.get('desc').strip()
        desc = desc.upper()

        if not name:
            flash("工作令号不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_jobnumber_create'), code=302)
        if not desc:
            flash("项目名称不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_jobnumber_create'), code=302)

        if Jobnumber.query.filter_by(name=name).first():
            flash("工作令号已存在。", category="danger")
            return redirect(url_for('bp_admin.admin_jobnumber_create'), code=302)

        try:
            jobnumber = Jobnumber(name=name,desc=desc)
            db.session.add(jobnumber)
            db.session.commit()
            flash("工作令号创建成功。", category="success")
            return redirect(url_for('bp_admin.admin_jobnumbers'), code=302)
        except Exception as e:
            flash(e, category="danger")
            return redirect(url_for('bp_admin.admin_jobnumber_create'), code=302)

@bp_admin.route("/admin/jobnumber/<jobnumberid>", methods=['GET','POST'])
@login_required
@admin_required
def admin_jobnumber_edit(jobnumberid):
    if request.method == 'GET':
        jobnumber = db.session.query(Jobnumber.id, Jobnumber.name, Jobnumber.desc).filter_by(id=jobnumberid).first()
        if jobnumber:
            return render_template('admin/jobnumber_edit.html',jobnumber=jobnumber)
        else:
            flash("工作令号不存在!", category="danger")
            return redirect(url_for('bp_admin.admin_jobnumbers'), code=302)

    if request.method == 'POST':
        name = request.form.get('name').strip()
        desc = request.form.get('desc').strip()

        if not name:
            flash("工作令号不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_jobnumber_edit',jobnumberid=jobnumberid), code=302)
        if not desc:
            flash("项目名称不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_jobnumber_edit',jobnumberid=jobnumberid), code=302)
        try:
            name = name.upper()
            jobnumber = Jobnumber.query.filter_by(id=jobnumberid).first()
            jobnumber.name = name
            jobnumber.desc = desc
            db.session.commit()
            flash("修改成功。", category="success")
            return redirect(url_for('bp_admin.admin_jobnumbers',jobnumberid=jobnumberid), code=302)
        except Exception as e:
            flash(e, category="danger")
            return redirect(url_for('bp_admin.admin_jobnumber_edit',jobnumberid=jobnumberid), code=302)

@bp_admin.route("/admin/jobnumber/<jobnumberid>/delete")
@login_required
@admin_required
def admin_jobnumber_delete(jobnumberid):
    jobnumber = Jobnumber.query.filter_by(id=jobnumberid).first()
    if not jobnumber:
        flash("用户不存在", category="danger")
        return redirect(url_for('bp_admin.admin_jobnumbers'), code=302)
    try:
        jobnumber.delete = not jobnumber.delete
        db.session.commit()
        flash("修改成功。" , category="success")
        return redirect(url_for('bp_admin.admin_jobnumbers'), code=302)
    except Exception as e:
        flash(e, category="danger")
        return redirect(url_for('bp_admin.admin_jobnumbers'), code=302)







# category routes....
@bp_admin.route("/admin/categories", methods=['GET'])
@login_required
@admin_required
def admin_categories():
    categories = db.session.query(Category.id, Category.name, Category.color, Category.delete).all()
    return render_template('admin/categories.html',categories=categories)

@bp_admin.route("/admin/category", methods=['GET','POST'])
@login_required
@admin_required
def admin_category_create():
    if request.method == 'GET':
        return render_template('admin/category_create.html')
    if request.method == 'POST':
        name = request.form.get('name').strip()
        color = request.form.get('color').strip()

        if not name:
            flash("大类不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_category_create'), code=302)

        if Category.query.filter_by(name=name).first():
            flash("大类已存在。", category="danger")
            return redirect(url_for('bp_admin.admin_category_create'), code=302)
        if not color:
            flash("颜色不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_category_create'), code=302)

        try:
            name = name.upper()
            category = Category(name=name, color=color)
            db.session.add(category)
            db.session.commit()
            flash("大类创建成功。", category="success")
            return redirect(url_for('bp_admin.admin_categories'), code=302)
        except Exception as e:
            flash(e, category="danger")
            return redirect(url_for('bp_admin.admin_category_create'), code=302)

@bp_admin.route("/admin/category/<categoryid>", methods=['GET','POST'])
@login_required
@admin_required
def admin_category_edit(categoryid):
    if request.method == 'GET':
        category = db.session.query(Category.id, Category.name, Category.color).filter_by(id=categoryid).first()
        if category:
            return render_template('admin/category_edit.html',category=category)
        else:
            flash("大类不存在!", category="danger")
            return redirect(url_for('bp_admin.admin_categories'), code=302)

    if request.method == 'POST':
        name = request.form.get('name').strip()
        color = request.form.get('color').strip()

        if not name:
            flash("大类不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_category_edit',categoryid=categoryid), code=302)
        if not color:
            flash("颜色不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_category_edit',categoryid=categoryid), code=302)

        try:
            name = name.upper()
            category = Category.query.filter_by(id=categoryid).first()
            category.name = name
            category.color = color
            db.session.commit()
            flash("修改成功。", category="success")
            return redirect(url_for('bp_admin.admin_categories',categoryid=categoryid), code=302)
        except Exception as e:
            flash(e, category="danger")
            return redirect(url_for('bp_admin.admin_category_edit',categoryid=categoryid), code=302)

@bp_admin.route("/admin/category/<categoryid>/delete")
@login_required
@admin_required
def admin_category_delete(categoryid):
    category = Category.query.filter_by(id=categoryid).first()
    if not category:
        flash("大类不存在", category="danger")
        return redirect(url_for('bp_admin.admin_categories'), code=302)
    try:
        category.delete = not category.delete
        db.session.commit()
        flash("修改成功。" , category="success")
        return redirect(url_for('bp_admin.admin_categories'), code=302)
    except Exception as e:
        flash(e, category="danger")
        return redirect(url_for('bp_admin.admin_categories'), code=302)


# subcategory routes....
@bp_admin.route("/admin/subcategories", methods=['GET'])
@login_required
@admin_required
def admin_subcategories():
    # subcategories = db.session.query(Subcategory.id, Subcategory.name, Subcategory.color, Subcategory.categoryid, Subcategory.delete).all()
    subcategories = db.session.query(Subcategory.id, Subcategory.name, Category.color, Subcategory.categoryid, Subcategory.delete, Category.name).join(Category, Subcategory.categoryid==Category.id).all()
    return render_template('admin/subcategories.html',subcategories=subcategories)

@bp_admin.route("/admin/subcategory", methods=['GET','POST'])
@login_required
@admin_required
def admin_subcategory_create():
    if request.method == 'GET':
        categories = db.session.query(Category.id, Category.name).filter_by(delete=False).all()
        return render_template('admin/subcategory_create.html', categories=categories)
    if request.method == 'POST':
        name = request.form.get('name').strip()
        color = request.form.get('color').strip()
        categoryid = request.form.get('categoryid').strip()

        if not categoryid:
            flash("大类不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_subcategory_create'), code=302)
        try:
            categoryid = int(categoryid)
        except:
            flash("大类id int only", category="danger")
            return redirect(url_for('bp_admin.admin_subcategory_create'), code=302)

        if not name:
            flash("分类不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_subcategory_create'), code=302)
        if not color:
            flash("颜色不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_subcategory_create'), code=302)
        if Subcategory.query.filter_by(name=name).first():
            flash("分类已存在。", category="danger")
            return redirect(url_for('bp_admin.admin_subcategory_create'), code=302)

        try:
            name = name.upper()
            subcategory = Subcategory(name=name, color=color, categoryid=categoryid)
            db.session.add(subcategory)
            db.session.commit()
            flash("分类创建成功。", category="success")
            return redirect(url_for('bp_admin.admin_subcategories'), code=302)
        except Exception as e:
            flash(e, category="danger")
            return redirect(url_for('bp_admin.admin_subcategory_create'), code=302)

@bp_admin.route("/admin/subcategory/<subcategoryid>", methods=['GET','POST'])
@login_required
@admin_required
def admin_subcategory_edit(subcategoryid):
    if request.method == 'GET':
        subcategory = db.session.query(Subcategory.id, Subcategory.name, Subcategory.color, Subcategory.categoryid).filter_by(id=subcategoryid).first()
        categories = db.session.query(Category.id, Category.name).filter_by(delete=False).all()
        if subcategory:
            return render_template('admin/subcategory_edit.html',subcategory=subcategory, categories=categories)
        else:
            flash("分类不存在!", category="danger")
            return redirect(url_for('bp_admin.admin_subcategories'), code=302)

    if request.method == 'POST':
        name = request.form.get('name').strip()
        color = request.form.get('color').strip()
        categoryid = request.form.get('categoryid').strip()

        try:
            categoryid = int(categoryid)
        except:
            flash("大类id int only", category="danger")
            return redirect(url_for('bp_admin.admin_subcategory_edit',subcategoryid=subcategoryid), code=302)
        if not name:
            flash("分类不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_subcategory_edit',subcategoryid=subcategoryid), code=302)
        if not color:
            flash("颜色不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_subcategory_edit',subcategoryid=subcategoryid), code=302)

        try:
            name = name.upper()
            subcategory = Subcategory.query.filter_by(id=subcategoryid).first()
            subcategory.name = name
            subcategory.color = color
            subcategory.categoryid = categoryid
            db.session.commit()
            flash("修改成功。", category="success")
            return redirect(url_for('bp_admin.admin_subcategories',subcategoryid=subcategoryid), code=302)
        except Exception as e:
            flash(e, category="danger")
            return redirect(url_for('bp_admin.admin_subcategory_edit',subcategoryid=subcategoryid), code=302)

@bp_admin.route("/admin/subcategory/<subcategoryid>/delete")
@login_required
@admin_required
def admin_subcategory_delete(subcategoryid):
    subcategory = Subcategory.query.filter_by(id=subcategoryid).first()
    if not subcategory:
        flash("分类不存在", category="danger")
        return redirect(url_for('bp_admin.admin_subcategories'), code=302)
    try:
        subcategory.delete = not subcategory.delete
        db.session.commit()
        flash("修改成功。" , category="success")
        return redirect(url_for('bp_admin.admin_subcategories'), code=302)
    except Exception as e:
        flash(e, category="danger")
        return redirect(url_for('bp_admin.admin_subcategories'), code=302)


# task routes....
@bp_admin.route("/admin/tasks", methods=['GET'])
@login_required
@admin_required
def admin_tasks():
    # tasks = db.session.query(Task.id, Task.name, Task.color, Task.categoryid, Task.delete).all()
    tasks = db.session.query(Task.id, Task.title, Task.remark, Task.userid, Task.categoryid, Task.subcategoryid, Task.jobnumberid, Task.manhour, Task.tasktime, Task.createtime, Task.edittime, Task.delete, User.name, Category.name, Subcategory.name, Jobnumber.name).join(Jobnumber, Jobnumber.id==Task.jobnumberid).join(User, User.id==Task.userid).join(Category, Category.id==Task.categoryid).join(Subcategory, Subcategory.id==Task.subcategoryid).all()
    # print(tasks[0],dir(tasks[0]),tasks[0]._fields)
    # we can valuate task[0].userid
    # But we can valuate task[0].user_name because it has username jobnumber name and they all call name
    # print(tasks.statement)
    # for attr in dir(tasks):
    #     print(attr, eval('tasks.{}'.format(attr)))
    return render_template('admin/tasks.html',tasks=tasks)

@bp_admin.route("/admin/task", methods=['GET','POST'])
@login_required
@admin_required
def admin_task_create():
    if request.method == 'GET':
        jobnumbers = db.session.query(Jobnumber.id, Jobnumber.name).filter_by(delete=False).all()
        categories = db.session.query(Category.id, Category.name).filter_by(delete=False).all()
        subcategories = db.session.query(Subcategory.id, Subcategory.name, Subcategory.categoryid, Category.name).filter_by(delete=False).join(Category, Category.id==Subcategory.categoryid).all()
        # 算法有点傻 待优化
        optgroup = {}
        for i in subcategories:
            cat = i[3]
            j = optgroup.get(cat)
            if j:
                j.append(i)
                tmp = {cat:j}
            else:
                tmp = {cat:[i]}
            optgroup.update(tmp)
        return render_template('admin/task_create.html', categories=categories, jobnumbers=jobnumbers, subcategories=subcategories,optgroup=optgroup)
    if request.method == 'POST':
        userid = current_user.id
        jobnumberid = request.form.get('jobnumberid')
        categoryid = request.form.get('categoryid')
        subcategoryid = request.form.get('subcategoryid')
        tasktime = request.form.get('tasktime')
        manhour = request.form.get('manhour')
        title = request.form.get('title')
        remark = request.form.get('remark')

        if not jobnumberid:
            flash("工作令号不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_task_create'), code=302)
        jobnumberid = jobnumberid.strip()
        if not categoryid:
            flash("大类不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_task_create'), code=302)
        categoryid = int(categoryid)
        if not subcategoryid:
            flash("分类不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_task_create'), code=302)
        subcategoryid = int(subcategoryid)
        if not tasktime:
            flash("任务日期不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_task_create'), code=302)
        tasktime = datetime.strptime(tasktime, '%m/%d/%Y')
        if not title:
            flash("任务不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_task_create'), code=302)
        if not manhour:
            flash("工时不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_task_create'), code=302)
        try:
            manhour = float(manhour)
        except:
            flash("工时必须是数字", category="danger")
            return redirect(url_for('bp_admin.admin_task_create'), code=302)

        if not remark:
            remark = ""


        task = Task(title=title, remark=remark, userid=userid, categoryid=categoryid, subcategoryid=subcategoryid, jobnumberid=jobnumberid, manhour=manhour, tasktime=tasktime, createtime=datetime.now())
        db.session.add(task)
        db.session.commit()
        flash("任务创建成功。", category="success")
        return redirect(url_for('bp_admin.admin_tasks'), code=302)

@bp_admin.route("/admin/task/<taskid>", methods=['GET','POST'])
@login_required
@admin_required
def admin_task_edit(taskid):
    if request.method == 'GET':
        task = db.session.query(Task.id, Task.jobnumberid, Task.categoryid, Task.subcategoryid, Task.tasktime, Task.manhour, Task.title, Task.remark).filter_by(id=taskid).first()
        if task:
            jobnumbers = db.session.query(Jobnumber.id, Jobnumber.name,Jobnumber.desc).filter_by(delete=False).all()
            categories = db.session.query(Category.id, Category.name).filter_by(delete=False).all()
            subcategories = db.session.query(Subcategory.id, Subcategory.name, Subcategory.categoryid, Category.name).filter_by(delete=False).join(Category, Category.id==Subcategory.categoryid).all()
            # 算法有点傻 待优化
            optgroup = {}
            for i in subcategories:
                cat = i[3]
                j = optgroup.get(cat)
                if j:
                    j.append(i)
                    tmp = {cat:j}
                else:
                    tmp = {cat:[i]}
                optgroup.update(tmp)
            return render_template('admin/task_edit.html',task=task, categories=categories, jobnumbers=jobnumbers, subcategories=subcategories,optgroup=optgroup)
        else:
            flash("任务不存在!", category="danger")
            return redirect(url_for('bp_admin.admin_tasks'), code=302)

    if request.method == 'POST':
        jobnumberid = request.form.get('jobnumberid')
        categoryid = request.form.get('categoryid')
        subcategoryid = request.form.get('subcategoryid')
        tasktime = request.form.get('tasktime')
        manhour = request.form.get('manhour')
        title = request.form.get('title')
        remark = request.form.get('remark')

        if not jobnumberid:
            flash("工作令号不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_task_edit', taskid=taskid), code=302)
        jobnumberid = jobnumberid.strip()
        if not categoryid:
            flash("大类不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_task_edit', taskid=taskid), code=302)
        categoryid = int(categoryid)
        if not subcategoryid:
            flash("分类不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_task_edit', taskid=taskid), code=302)
        subcategoryid = int(subcategoryid)
        if not tasktime:
            flash("任务日期不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_task_edit', taskid=taskid), code=302)
        tasktime = datetime.strptime(tasktime, '%m/%d/%Y')
        if not title:
            flash("任务不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_task_edit', taskid=taskid), code=302)
        if not manhour:
            flash("工时不能为空", category="danger")
            return redirect(url_for('bp_admin.admin_task_edit', taskid=taskid), code=302)
        try:
            manhour = float(manhour)
        except:
            flash("工时必须是数字", category="danger")
            return redirect(url_for('bp_admin.admin_task_edit', taskid=taskid), code=302)

        if not remark:
            remark = ""

        task = Task.query.filter_by(id=taskid).first()
        task.title=title
        task.remark=remark
        task.categoryid=categoryid
        task.subcategoryid=subcategoryid
        task.jobnumberid=jobnumberid
        task.manhour=manhour
        task.tasktime=tasktime
        task.edittime=datetime.now()

        db.session.commit()
        flash("修改成功。", category="success")
        return redirect(url_for('bp_admin.admin_tasks',taskid=taskid), code=302)

@bp_admin.route("/admin/task/<taskid>/delete")
@login_required
@admin_required
def admin_task_delete(taskid):
    task = Task.query.filter_by(id=taskid).first()
    if not task:
        flash("分类不存在", category="danger")
        return redirect(url_for('bp_admin.admin_tasks'), code=302)
    task.delete = not task.delete
    task.edittime=datetime.now()
    db.session.commit()
    flash("修改成功。" , category="success")
    return redirect(url_for('bp_admin.admin_tasks'), code=302)





if __name__ == '__main__':

    pass